package cn.myfirefly.moming.portal.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.myfirefly.moming.common.model.MenuDto;
import cn.myfirefly.moming.common.model.MenuResultDto;
import cn.myfirefly.moming.portal.dao.FunctionDao;
import cn.myfirefly.moming.portal.dao.SystemAccessDao;
import cn.myfirefly.moming.portal.entity.MMFunction;
import cn.myfirefly.moming.portal.entity.MMSystemAccess;
import cn.myfirefly.moming.portal.model.FunctionDto;
import cn.myfirefly.moming.portal.model.FunctionFilterDto;
import cn.myfirefly.core.Const;
import cn.myfirefly.core.model.PageResultDto;
import cn.myfirefly.utils.BeanUtil;
import cn.myfirefly.utils.CollectionUtil;
import cn.myfirefly.utils.StrUtil;

@Service
@Transactional
public class FunctionService {
//	private Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private FunctionDao functionDao;
	
	@Autowired
	private SystemAccessDao systemAccessDao;
	
	public PageResultDto<MMFunction> getList(FunctionFilterDto dto, Integer systemId) {
		return functionDao.getList(dto, systemId);
	}
	
	public String save(FunctionDto dto) {
		MMFunction func = functionDao.getByCode(dto.getFunId());
		// 更新
		if (StrUtil.notBlank(dto.getFunSn())) {
			if (func == null) {
				return "功能菜单不存在，请刷新页面后重试。";
			}
			if (func != null && !func.getFunSn().equals(dto.getFunSn())) {
				return "功能菜单已存在。";
			}
		} else {
		// 新增
			if (func != null) {
				return "功能菜单已存在。";
			} 
			func = new MMFunction();
			func.setCreateBy(dto.getModifyBy());
			func.setCreateDate(dto.getModifyDate());
		}
		BeanUtil.copyBeans(dto, func);
		if (StrUtil.notBlank(dto.getDisplayFlag())) {
			func.setDisplayFlag(dto.getDisplayFlag().charAt(0));
		} else {
			func.setDisplayFlag('N');
		}
		functionDao.save(func);
		return Const.ResultCode.SUCCESS;
	}
	
	public FunctionDto getFunction(Integer funSn) {
		MMFunction func = functionDao.get(funSn);
		return BeanUtil.copyBeans(FunctionDto.class, func);
	}
	
	public String del(Integer funSn) {
		MMFunction func = functionDao.get(funSn);
		if (func == null) {
			return "功能菜单不存在，请刷新页面后重试。";
		}
		if (func != null && func.getFunSn() != funSn) {
			return "功能菜单已变更，请刷新页面后重试。";
		}
		List<MMFunction> list = functionDao.getChildren(func.getFunId());
		if (list != null && list.size() > 0) {
			return "功能菜单下有子菜单，不能进行删除。";
		}
		
		functionDao.del(func);
		return Const.ResultCode.SUCCESS;
	}
	
	public List<MenuDto> getAllMenus() {
		List<MMSystemAccess> systemAccessList = systemAccessDao.getSystemAccessList('1');
		StringBuffer inSysId = new StringBuffer();
		if (CollectionUtil.isNotEmpty(systemAccessList)) {
			int size = systemAccessList.size();
			for (int i = 0; i < size; i++) {
				if (i + 1 >= size) {
					inSysId.append(systemAccessList.get(i).getSystemId());
				} else {
					inSysId.append(systemAccessList.get(i).getSystemId());
					inSysId.append(",");
				}
			}
		}
		List<MenuDto> menuList = functionDao.getAllMenus(inSysId.toString());
		MenuDto dto = null;
		for (MMSystemAccess systemAccess : systemAccessList) {
			if (systemAccess.getPermissionType() == '1') {
				dto = new MenuDto();
				dto.setId(systemAccess.getSystemId().toString());
				dto.setName(systemAccess.getSystemName());
				dto.setPId(null);
				dto.setUrl(null);
				dto.setOpenIcon("fa fa-table");
				dto.setCloseIcon("folder-o");
				dto.setFunIndex(systemAccess.getShowIndex());
				menuList.add(dto);
			}
		}
		return menuList;
	}
	
	public List<MenuResultDto> getMenus(String loginName, Integer systemId) {
		MMSystemAccess systemAccess = systemAccessDao.getBySysId(systemId);
		List<MenuResultDto> result = new ArrayList<MenuResultDto>();
		
		if (systemAccess != null) {
			MenuDto topMenu = new MenuDto();
			topMenu.setId(systemAccess.getSystemId().toString());
			topMenu.setName(systemAccess.getSystemName());
			topMenu.setPId("");
			topMenu.setUrl("");
			topMenu.setFunIndex(systemAccess.getShowIndex());
			
			// 取得所有有权限的叶子节点
			List<MenuDto> menuDtos = functionDao.getMenus(loginName, systemId);
			List<MenuDto> resultMenuList = new ArrayList<>();
			if (CollectionUtil.isNotEmpty(menuDtos)) {
				// 取得所有菜单
				List<MenuDto> allMenu = functionDao.getAllMenus(systemId);
				// 将叶子节点复制到resultMenuList中
				resultMenuList.addAll(menuDtos);
				
				for(MenuDto t : menuDtos){
					//找父级菜单，直到找到顶级菜单为止
					findParentMenu(t, allMenu, resultMenuList);
				}
				Collections.sort(resultMenuList, new Comparator<MenuDto>() {
					public int compare(MenuDto o1, MenuDto o2) {
						return o1.getFunIndex() - o2.getFunIndex();
					}
				});
				MenuResultDto menuResultDto = new MenuResultDto();
				menuResultDto.setFunId(topMenu.getId());
				menuResultDto.setMenuDto(topMenu);
				menuResultDto.setMenuList(resultMenuList);
				result.add(menuResultDto);
			}
		}
		return result;
	}
	
	public List<MenuResultDto> getMenus(Integer systemId) {
		MMSystemAccess systemAccess = systemAccessDao.getBySysId(systemId);
		List<MenuResultDto> result = new ArrayList<MenuResultDto>();
		
		if (systemAccess != null) {
			MenuDto topMenu = new MenuDto();
			topMenu.setId(systemAccess.getSystemId().toString());
			topMenu.setName(systemAccess.getSystemName());
			topMenu.setPId("");
			topMenu.setUrl("");
			topMenu.setFunIndex(systemAccess.getShowIndex());
			List<MenuDto> menuDtos = functionDao.getMenus(systemId);
			MenuResultDto menuResultDto = null;
			if (CollectionUtil.isNotEmpty(menuDtos)) {
				menuResultDto = new MenuResultDto();
				menuResultDto.setFunId(topMenu.getId());
				menuResultDto.setMenuDto(topMenu);
				menuResultDto.setMenuList(menuDtos);
				result.add(menuResultDto);
			}
		}
		
		return result;
	}
	
	private void findParentMenu(MenuDto menuDto,  List<MenuDto> allMenuList, List<MenuDto> targetMenuList) {
		if (menuDto.getRecursiveLevel() < 10) {
			// 为了避免死循环，限制递归次数，最大为10
			for (MenuDto tempMenuDto : allMenuList) {
				if (StrUtil.equals(menuDto.getpId(), tempMenuDto.getId())) {
					tempMenuDto.setRecursiveLevel(menuDto.getRecursiveLevel() + 1);
//					System.out.println("当前递归次数：" + tempMenuDto.getRecursiveLevel());
					if (existMenu(tempMenuDto.getId(), targetMenuList)) {
					} else {
						targetMenuList.add(tempMenuDto);
					}
					if (StrUtil.notBlank(tempMenuDto.getpId())) {
						findParentMenu(tempMenuDto, allMenuList, targetMenuList);
					}
				}
			}
		}
	}
	
	private boolean existMenu(String funId, List<MenuDto> targetMenuList) {
		for (MenuDto menuDto : targetMenuList) {
			if (StrUtil.equals(funId, menuDto.getId())) {
				return true;
			}
		}
		return false;
	}
}
